package com.ziyun.erp.modules.goods.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.utility.New;
import com.ziyun.erp.common.utils.GoodsMonitorUtils;
import com.ziyun.erp.modules.goods.VO.TempOptionVO;
import com.ziyun.erp.modules.goods.dao.GoodsAttributeDao;
import com.ziyun.erp.modules.goods.dao.GoodsTemplateDao;
import com.ziyun.erp.modules.goods.entity.GoodsAttributeEntity;
import com.ziyun.erp.modules.goods.entity.GoodsOptionEntity;
import com.ziyun.erp.modules.goods.entity.GoodsTemplateEntity;
import com.ziyun.erp.modules.goods.service.GoodsOptionService;
import com.ziyun.erp.modules.goods.service.GoodsTemplateService;
import com.ziyun.erp.modules.goodsCategory.dao.GoodsCategoryDao;
import com.ziyun.erp.modules.goodsMonitor.entity.GoodsMonitorEntity;
import com.ziyun.erp.modules.goodsMonitor.service.GoodsMonitorService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("goodsTemplateService")
public class GoodsTemplateServiceImpl extends ServiceImpl<GoodsTemplateDao, GoodsTemplateEntity> implements GoodsTemplateService {

    @Autowired
    private GoodsTemplateDao goodsTemplateDao;

    @Autowired
    private GoodsAttributeDao goodsAttributeDao;

    @Autowired
    private GoodsCategoryDao goodsCategoryDao;

    @Autowired
    private GoodsOptionService goodsOptionService;

    @Autowired
    private GoodsMonitorService goodsMonitorService;

    @Override
//    @DataSource(name = DataSourceNames.SECOND)
    public PageUtils queryPage(Map<String, Object> params) {
        Integer templateId = StringUtil.getRequestParamInteger(params.get("templateId"));
        String templateName = StringUtil.getRequestParamString(params.get("templateName"));
        Page<GoodsTemplateEntity> page = this.selectPage(
                new Query<GoodsTemplateEntity>(params).getPage(),
                new EntityWrapper<GoodsTemplateEntity>()
                .orderBy("template_id",false)
                .eq("disabled",0)
                .eq(templateId != null,"template_id",templateId)
                .like(StringUtils.isNotBlank(templateName),"template_name",templateName)
        );

        return new PageUtils(page);
    }

    /**
     * 标记删除商品模板
     * @param templateIds
     */
    @Override
//    @DataSource(name = DataSourceNames.SECOND)
//    @Transactional(value = "secondTransactionManager", rollbackFor = Exception.class)
    public void fagDeleteByTemplateIds(Long[] templateIds) {
        goodsTemplateDao.fagDeleteByTemplateIds(templateIds);
    }

    @Override
//    @DataSource(name = DataSourceNames.SECOND)
    //查询所有模板
    public List<GoodsTemplateEntity> selectAllTemplate() {
        List<GoodsTemplateEntity> list = goodsTemplateDao.selectAllTemplate();
        return list;
    }

    @Override
//    @DataSource(name = DataSourceNames.SECOND)
    public void setAttributeNames(List<GoodsTemplateEntity> allTemplate) {
        for (int i = 0;i<allTemplate.size();i++){
            String attributeIds = allTemplate.get(i).getAttributeIds();
            String attributeNames = goodsAttributeDao.getAttributeNamesByAttributeIds(attributeIds);
            allTemplate.get(i).setAttributeNames(attributeNames);
        }
    }

    @Override
//    @DataSource(name = DataSourceNames.SECOND)
    //根据catId返回模板对象
    public GoodsTemplateEntity getTemplateByCatId(Integer catId) {
        GoodsTemplateEntity goodTemplate = goodsTemplateDao.getTemplateByCatId(catId);
        return goodTemplate;
    }

    @Override
//    @DataSource(name = DataSourceNames.SECOND)
    public String getAttributeTypes(Long templateId) {
        String str = goodsTemplateDao.getAttributeTypes(templateId);
        return str;
    }

    /**
     * 保存模板对象,获得返回值
     * @param goodsTemplate
     * @return
     */
    @Override
//    @DataSource(name = DataSourceNames.SECOND)
//    @Transactional(value = "secondTransactionManager", rollbackFor = Exception.class)
    public Integer saveTemplate(GoodsTemplateEntity goodsTemplate) {
        Integer id = goodsTemplateDao.saveTemplate(goodsTemplate);
        return id;
    }

    @Override
    /**
     * 保存模板对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(GoodsTemplateEntity goodsTemplate) {
        checkGoodsTemplate(goodsTemplate);
//        goodsTemplate.setCreateName(UserUtils.getCurentUser().getUsername());
        goodsTemplateDao.insert(goodsTemplate);
        Integer categoryId = goodsTemplate.getCategoryId();
        Long templateId = goodsTemplate.getTemplateId();
        //更新分类表
        if(categoryId != null){
            goodsCategoryDao.updateTemplateId(templateId,categoryId);
        }else{
            System.out.println("更新模板失败!");
        }
    }

    private void checkGoodsTemplate(GoodsTemplateEntity goodsTemplate) {
        long attributeId = goodsTemplate.getInfluenceSkuTotalPrice();
        List<GoodsOptionEntity> goodsOptionEntityList = goodsOptionService.loadTempOptionsByAttributeId(attributeId);
        for (GoodsOptionEntity goodsOptionEntity : goodsOptionEntityList) {
            try{
                String optionValue = goodsOptionEntity.getOptionValue();
                Integer i = Integer.parseInt(optionValue);
            }catch (NumberFormatException e){
                throw new RRException("当前模板绑定的影响sku算价规格值中,含有非数字选项,请核查!");
            }
        }
    }

    @Override
    public String getInfluenceCraftIds(Integer categoryId) {
        return goodsTemplateDao.getInfluenceCraftIds(categoryId);
    }

    @Override
    public Map<String, List> loadTempOptionsList(Long[] attributeIds) {
        Map<String, List> map = New.hashMap();
        List<TempOptionVO> tempOptionVOList = new ArrayList<>();
        List<TempOptionVO> tempCraftOptionVOList = new ArrayList<>();
        List<GoodsAttributeEntity> attributeList = new ArrayList<>();
        for(int i = 0;i <attributeIds.length;i++){
            TempOptionVO tempOptionVO = new TempOptionVO();
            tempOptionVO.setAttributeId(attributeIds[i]);
            GoodsAttributeEntity goodsAttributeEntity = goodsAttributeDao.selectById(attributeIds[i]);
            tempOptionVO.setGoodsAttributeEntity(goodsAttributeEntity);
            tempOptionVO.setAttributeName(goodsAttributeEntity.getAttributeName());
            tempOptionVO.setGoodsOptionList(goodsOptionService.loadTempOptionsByAttributeId(attributeIds[i]));
            if("normal".equals(goodsAttributeEntity.getAttributeType())){
                tempOptionVOList.add(tempOptionVO);
                attributeList.add(goodsAttributeEntity);
            }else if("craft".equals(goodsAttributeEntity.getAttributeType())){
                tempCraftOptionVOList.add(tempOptionVO);
            }
        }
        map.put("attributeVOList",tempOptionVOList);
        map.put("craftVOList",tempCraftOptionVOList);
        map.put("attributeList",attributeList);
        return map;
    }

    /**
     * 处理数据
     * @param goodsTemplate
     * @return
     */
    @Override
    public Map<String, List> handlerOptionJson(GoodsTemplateEntity goodsTemplate) {
        String optionJson = goodsTemplate.getOptionJson();
        long influenceSkuTotalPrice = goodsTemplate.getInfluenceSkuTotalPrice();
        //influence_craft_ids
        String influenceCraftIds = goodsTemplate.getInfluenceCraftIds();
        JSONArray jsonArray = JSONArray.fromObject(optionJson);
        JSONArray influenceCraftArray = new JSONArray();
        if(StringUtils.isNotBlank(influenceCraftIds)){
            influenceCraftArray = JSONArray.fromObject(influenceCraftIds);
        }
        Map<String, List> map = New.hashMap();
        List<TempOptionVO> tempOptionVOList = new ArrayList<>();
        List<TempOptionVO> tempCraftOptionVOList = new ArrayList<>();
        List<GoodsAttributeEntity> attributeList = new ArrayList<>();
        for(int i = 0;i<jsonArray.size();i++){
            TempOptionVO tempOptionVO = new TempOptionVO();
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Long attributeId = Long.valueOf(jsonObject.get("attributeId").toString());
            JSONArray optionId = jsonObject.getJSONArray("optionId");
            tempOptionVO.setAttributeId(attributeId);
            //影响sku总价计算的规格
            if(attributeId == influenceSkuTotalPrice){
                tempOptionVO.setInfluenceCraft(true);
            }else{
                tempOptionVO.setInfluenceCraft(false);
            }
            //根据该规格查出所有的选项
            GoodsAttributeEntity goodsAttributeEntity = goodsAttributeDao.selectById(attributeId);
            tempOptionVO.setAttributeName(goodsAttributeEntity.getAttributeName());
            tempOptionVO.setAttributeType(goodsAttributeEntity.getAttributeType());
            tempOptionVO.setGoodsAttributeEntity(goodsAttributeEntity);
            tempOptionVO.setGoodsOptionList(goodsOptionService.loadTempOptionsByAttributeId(attributeId));
            tempOptionVO.setSelectedOptionList(optionId);
            if("normal".equals(goodsAttributeEntity.getAttributeType())){
                tempOptionVOList.add(tempOptionVO);
                attributeList.add(goodsAttributeEntity);
            }else if("craft".equals(goodsAttributeEntity.getAttributeType())){
                tempCraftOptionVOList.add(tempOptionVO);
                //工艺类型的需要设置影响他的规格
                if(influenceCraftArray.size() != 0){
                    Boolean flag = true;
                    for(int j = 0;j<influenceCraftArray.size();j++){
                        JSONObject influenceCraft = influenceCraftArray.getJSONObject(j);
                        if(Integer.parseInt(influenceCraft.getString("craftId")) == attributeId){
                            tempOptionVO.setInfluenceAttributeIds(influenceCraft.getJSONArray("attributeIds"));
                            flag = false;
                        }
                    }
                    //下列一段为死亡代码,为了保证程序鲁棒性,添加
                    if(flag){
                        tempOptionVO.setInfluenceAttributeIds(new ArrayList<>());
                    }
                }else{
                    //若没有配置,则也应返回一个空集合,而不是null
                    tempOptionVO.setInfluenceAttributeIds(new ArrayList<>());
                }
            }
        }
        map.put("attributeVOList",tempOptionVOList);
        map.put("craftVOList",tempCraftOptionVOList);
        map.put("attributeList",attributeList);
        return map;
    }

    @Override
    public List<GoodsTemplateEntity> selectGoodsTemplateList(Integer attributeId) {
        return this.baseMapper.selectList(new EntityWrapper<GoodsTemplateEntity>()
                .where("find_in_set({0},craft_ids)", attributeId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGoodsTemplate(GoodsTemplateEntity goodsTemplate,Long userId) {
        checkGoodsTemplate(goodsTemplate);
        GoodsTemplateEntity oldGoodsTemplate = this.baseMapper.selectById(goodsTemplate.getTemplateId());
        GoodsMonitorEntity goodsMonitorEntity = GoodsMonitorUtils.packingData(oldGoodsTemplate, goodsTemplate, userId);
        if(goodsMonitorEntity.getSdbId() != null){
            goodsMonitorService.insert(goodsMonitorEntity);
        }
        this.updateAllColumnById(goodsTemplate);//全部更新
    }
}
